package com.gitee.cirnochat.common.service.impl;

import com.gitee.cirnochat.common.config.EmailConfig;
import com.gitee.cirnochat.common.model.enums.EmailSendType;
import com.gitee.cirnochat.common.service.EmailService;
import com.gitee.cirnochat.common.utils.VerifyCodeUtils;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import static com.gitee.cirnochat.common.constant.EmailConstant.*;
import static com.gitee.cirnochat.common.constant.RedisKey.EMAIL_LOGIN_CAPTCHA_CACHE_KEY;
import static com.gitee.cirnochat.common.constant.RedisKey.EMAIL_RESET_PASS_CAPTCHA_CACHE_KEY;
import static com.gitee.cirnochat.common.utils.EmailUtil.buildEmailContent;

@Service
@RequiredArgsConstructor
@Slf4j
public class EmailServiceImpl implements EmailService {
    private final StringRedisTemplate redisTemplate;
    private final JavaMailSender mailSender;
    private final EmailConfig emailConfig;

    /**
     * 发送邮箱登录验证码
     * @param email 邮箱验证码 用于发送验证码
     */
    @Async
    @Override
    public void sendCaptchaAsync(String email, EmailSendType sendType) {
        try {
            // 邮箱发送内容组成
            MimeMessage message = mailSender.createMimeMessage();
            // 生成6位数字验证码
            String code = VerifyCodeUtils.generateNumericCode(6);
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setSubject(EMAIL_SUBJECT);
            helper.setText(buildEmailContent(EMAIL_HTML_CONTENT_PATH, code), true);
            helper.setTo(email);
            helper.setFrom(EMAIL_TITLE + '<' + emailConfig.getEmailFrom() + '>');
            //将验证码保存到redis以便于与用户核对
            redisTemplate.opsForValue().set(getCacheKey(sendType) + email, code, EMAIL_VERIFY_CODE_EXPIRE_TIME);
            //发送邮件
            mailSender.send(message);
            log.debug("发送验证码到邮箱: {}, 验证码: {} , 类型：{}", email, code, sendType);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取验证码缓存键
     *
     * @param sendType 发送事件类型
     * @return 验证码缓存键
     */
    private static String getCacheKey(EmailSendType sendType) {
        String cacheKey;
        switch (sendType) {
            case EmailSendType.LOGIN_OR_REGISTER -> cacheKey = EMAIL_LOGIN_CAPTCHA_CACHE_KEY;
            case EmailSendType.RESET_PASSWORD -> cacheKey = EMAIL_RESET_PASS_CAPTCHA_CACHE_KEY;
            default -> throw new IllegalStateException("Unexpected value: " + sendType);
        }
        return cacheKey;
    }
}
